package com.ericsson;

import javax.annotation.Resource;
import javax.servlet.sip.SipServlet;
import javax.servlet.sip.SipFactory;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.sip.SipServletRequest;

@javax.servlet.sip.annotation.SipServlet
public class HelloWorldServlet extends SipServlet {
	/**
	 * Serial version UID.
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * The SIP Factory. Can be used to create URI and requests.
	 */
	@Resource
	private SipFactory sipFactory;

	/**
	 * @inheritDoc
	 */
	protected void doMessage(SipServletRequest req)
			throws ServletException, IOException {
		//TODO: Implement this method
		if (!"sip:greetings@ericsson.com"
				.equals(req.getRequestURI().toString())) {
			return;
		}
		// Send 200 OK to acknowledge request was received.
		req.createResponse(200).send();

		// Create a greeting MESSAGE to send back to the user.
		SipServletRequest messageRequest = sipFactory
				.createRequest(req.getApplicationSession(), "MESSAGE", req
						.getTo(), req.getFrom());
		messageRequest.pushRoute(sipFactory
				.createSipURI(null, "127.0.0.1:5082"));
		messageRequest.addHeader("Accept-Contact", req
				.getHeader("Accept-Contact"));
		messageRequest.addHeader("User-Agent", req.getHeader("User-Agent"));

		// Set the message content.
		messageRequest.setContent("Hello, World!", "text/plain");

		// S-CSCF processes only asserted requests. When a request is
		// sent without a P-Asserted-Identity header, it is rejected
		// with a 403 Forbidden. This header asserts that the request
		// comes from a trusted domain.
		messageRequest.addHeader("p-asserted-identity",
				"sip:helloworld@ericsson.com");

		// Send the request
		messageRequest.send();

	}
}
